<template>

  <el-dialog :title="title" :close-on-click-modal="false" :close-on-press-escape="false" v-model="open"
    class="form-dialog  form-dialog-large" append-to-body v-loading="!formInitialed">
    <el-form ref="editForm" :model="form" :rules="rules" label-width="120px" v-if="formInitialed">

      <el-row>
        <el-col :span="24">
          <el-form-item label="商品分类" prop="二级类目">
            <el-select class="category-first" v-model="form['一级类目']" placeholder="一级类目" style="width: 160px">
              <el-option v-for="(option, idx) in categories" :key="idx" :label="option.name" :value="option.id" />
            </el-select>

            <el-select class="category-second" v-if="form['一级类目']" v-model="form['二级类目']" placeholder="二级类目"
              style="width: 160px">
              <el-option
                v-for="(option, idx) in categories.filter(category => category.id === form['一级类目'])[0].children"
                :key="idx" :label="option.name" :value="option.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="columnSpan">
          <el-form-item label="日期" prop="日期">
            <el-date-picker v-model="form['日期']" type="date" placeholder="请选择日期" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="columnSpan">
          <el-form-item label="佣金" prop="佣金">
            <el-input-number class="commission" :min="0" :max="100" v-model="form['佣金']" type="date"
              placeholder="请输入佣金" /> %
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="columnSpan">
          <el-form-item label="产品链接" prop="产品链接">
            <el-input v-model="form['产品链接']" placeholder="请输入产品链接" @input="onLinkChange" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="columnSpan">
          <el-form-item label="产品名称" prop="产品名称">
            <el-input v-model="form['产品名称']" placeholder="请输入产品名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="columnSpan">
          <el-form-item label="商家名称" prop="">
            <el-input v-model="form['商家名称']" placeholder="请输入商家名称" />
          </el-form-item>
        </el-col>
      </el-row>



    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(editForm)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>

</template>
<script setup lang="ts">
import { ref, reactive, watch, toRefs, onMounted } from 'vue'
import * as categoryService from '@/api/service/CategoryService'
import * as dailyService from '@/api/service/DailyService'
import type { FormInstance } from 'element-plus'

const globalVal = globalThis as any;


defineOptions({ name: "DailyForm" });

const props = defineProps({
  item: {
    type: Object
  }
})

const editForm = ref<FormInstance>()
const emit = defineEmits(['update:item', 'success'])


const formInitialed = ref(false)
const columnSpan = ref(24);
const categories = ref<any>([])
const open = ref(true)
let links: string[] = []
let oldLink = null
const title = ref(props.item?.recordId ? '修改日常选品' : '新增日常选品')
const data = reactive({
  form: {
    recordId: null,
    '日期': new Date(),
    '产品链接': '',
    '产品名称': '',
    '商家名称': '',
    '一级类目': '',
    '二级类目': '',
    '佣金': ''
  },
  rules: {
    '产品链接': [{ required: true, message: "产品链接不能为空", trigger: "blur" }],
    '产品名称': [{ required: true, message: "产品名称不能为空", trigger: "blur" }],
    '一级类目': [{ required: true, message: "一级类目不能为空", trigger: "chane" }],
    '二级类目': [{ required: true, message: "二级类目不能为空", trigger: "chane" }]
  }
})

const { form, rules } = toRefs(data)

function reset(): void {
  data.form = {
    recordId: null,
    '日期': new Date(),
    '产品链接': '',
    '产品名称': '',
    '商家名称': '',
    '一级类目': data.form['一级类目'],
    '二级类目': data.form['二级类目'],
    '佣金': ''
  }
}

/**
 * 初始化
 */
function init(recordId?: number): void {
  categoryService.categories().then(items => {
    categories.value = items
  }).finally(() => {
    formInitialed.value = true
  });

  (async () => {
    for await (const page of await dailyService.findList()) {
      page.items.forEach(item => {
        links.push(item.fields['产品链接'].link);
      })
    }
  })()


  // todo
  if (recordId) {
    form.value = { ...props.item } as any
  }
  else {
    formInitialed.value = true;
  }

}

function onLinkChange(): void {
  let link = form.value['产品链接'];
  const arr = link.split(' ');

  link = arr[0];
  if (links.includes(link) && link !== oldLink) {
    globalVal.error(`链接${link}已存在表中`);
    setTimeout(() => {
      form.value['产品链接'] = ''
    }, 500)
    return;
  }
  if (arr.length === 2) {
    let text = arr[1];
    const match = text.match(/打开【快手】直接观看！【([^】]+)】推荐：([^。]+)/);
    if (match) {
      form.value['商家名称'] = match[1];
      form.value['产品名称'] = match[2];
    }


  }
  form.value['产品链接'] = link;

}

/**
 * 提交
 */
function submitForm(formEl: FormInstance|undefined): void {
  if(!formEl){
    return ;
  }
  formEl.validate(valid => {
    if (valid) {
      globalVal.showLoading()
      if (form.value.recordId != undefined) {

        dailyService.updateRecord(form.value.recordId, form.value).then(response => {
          if(response.code !== 0){
            throw new Error(response.msg)
          }
          globalVal.success("修改成功");
          open.value = false;
          emit('success', response.data.record)

        }).catch(e => {
          console.log(e);
          globalVal.error('修改失败')
        }).finally(() => {
          globalVal.hideLoading()
        });
      } else {
        dailyService.addRecord(form.value).then(response => {
          if(response.code !== 0){
            throw new Error(response.msg)
          }
          globalVal.success("新增成功");
          //open.value = false;
          emit('success', response.data.record)
          links.push(form.value['产品链接'])
          reset();
        }).catch(e => {
          console.log(e);
          globalVal.error('新增失败')
        }).finally(() => {
          globalVal.hideLoading()
        });
      }
    }
  });
}

/**
 * 取消
 */
function cancel(): void {
  open.value = false;
}

watch(open, (newVal) => {
  if (!newVal) {
    emit('update:item', null)
  }
})

onMounted(() => {
  reset();


  if (props.item?.recordId) {

    oldLink = props.item['产品链接']
    init(props.item.recordId);
  }
  else {
    init();
  }
})

</script>
<style lang="scss" scoped>
.category-second {
  margin-left: 10px;
}

.commission {
  margin-right: 10px;
}
</style>
